<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";



class ClientsClass extends IPlugin 
{
    var $color;
    
    function ClientsClass($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "darkgray";
    }
    
    function getPluginTag() { return "clientsclass"; }
    function getPluginName() { return "Clients Class Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuBlockTitle", "MenuTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Clients management"; } break;
            case "MenuTitle" : { return "Clients list"; } break;
        };
        return $result;
    }

    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------
    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        
        $core = getCoreInstance();
        $arg = $core->getGET();
        $db = $core->getProperty("db");
        
        switch ($_POST['event'])
        {
            case "EditClient":

                    $client_id = $_POST['client_id'];
                    unset($_POST['client_id']);
                    
                    $sql = "select count(*) from clients where client_email = '" . str2db($_POST['client_email'])."' and client_id <> {$client_id}";
                    if (0 != $db->getOne($sql))
                    {
                        $_GET['page'] = "edit";
                        $_GET['id'] = $client_id;
                        $_GET['error'] = "email";
                        return;
                    }
                    
                    $sql = "select count(*) from clients where client_id = {$client_id} and client_password = password('" . str2db($_POST['old_client_password']) . "')";
                    if ("" != $_POST['old_client_password'] && 0 == $db->getOne($sql))
                    {
                        $_GET['page'] = "edit";
                        $_GET['id'] = $client_id;
                        $_GET['error'] = "password";
                        return;
                    }
                    
                    unset($_POST['event']);
                    $password = "";
                    if ("" != $_POST['client_password'])
                    {
                        $password = ", client_password = password('" . str2db($_POST['client_password']) . "')";
                    }
                    unset($_POST['client_password']);
                    unset($_POST['old_client_password']);
                    unset($_POST['re_client_password']);

                    $timest = getdate(strtotime($_POST['client_birthday']));
                    $gm = gmdate ("Y-m-d",$timest[0]);
                    $_POST['client_birthday'] = $gm;
                    $timest = getdate(strtotime($_POST['client_ccexpdate']));
                    $gm = gmdate ("Y-m-d",$timest[0]);
                    $_POST['client_ccexpdate'] = $gm;
                    
                    $str_mail_groups = "";
                    if (isset($_POST['mail_groups']))
                    {
                        foreach ($_POST['mail_groups'] as $mail_group)
                        {
                            $str_mail_groups .= "<{$mail_group}>";
                        }
                        unset($_POST['mail_groups']);
                    }
                    $str_mail_groups = ", mail_groups = '" . $str_mail_groups . "'";
                    
                    $sql_params = "";
                    foreach ($_POST as $k => $v)
                    {
                        $sql_params .= ($sql_params == "" ? "" : ", ") . "{$k} = '" . str2db($v) . "'";
                    }

                    $sql = "update clients set " . $sql_params . $password . $str_mail_groups.  " where client_id = " . $client_id;
                    $db->Exec($sql);

                break;
            



                default :
                    break;
        }

        
        switch ($_GET['action'])
        {
                case "doDeleteClient" :
                    $sql = "delete from clients where client_id = " . $_GET['id'];
                    $db->Exec($sql);
                    break;
                
    
    
    
                default :
                    break;
        }
        
        
        return true;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = getCoreInstance();
        $render = $core->framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);
        $db = $core->getProperty("db");

        $page = "";

        switch ($_G["page"]) {
            
            case "edit":
                $page = $this->renderClientsEditPage($core, $render, $db);
                break;

            default:
                $page = $this->renderClientsList($core, $render, $db);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }

    // ----------------------------------------------------------------------------------
    // --- [ Render Clients List page ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    function renderClientsList(&$core, &$render, &$db)
    {
        $pg = &$core->getSnippet("paginator");

        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cl_rndCC,
                    "urlbase" => $this->getURL(),
                    "caption" => "Clients list",
                    "emptymsg" => "<center>No registered customers yet</center>",
                    "header" => array("ID", "Client Name","Client Email", "Client Phone", "Client Birthday", "Actions"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select client_id, client_name, client_email, client_phone, client_birthday from clients where client_name != 'noone' and client_name != 'Administrator' ",
                    "sql_count" => "select count(*) from clients  where client_name != 'noone' and client_name != 'Administrator'",
                    "ippg" => 20, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    );

        $HTML = $pg->Render($params);
        $render->assign("clients", $HTML);
        //debug($_SESSION);
        return "clients_list.tpl.php";
    }


    function cl_rndCC($data)
    {
        $str_get = "";
        foreach ($_GET as $k => $v)
        {
            $str_get .= ($str_get == "" ? "" : "&") . "{$k}=" . str2db($v);
        }
     
        $dt = array(
                array($data["client_id"], ""),
                array($data["client_name"], ""),
                array($data["client_email"], ""),
                array($data["client_phone"], ""),
                array(date("m/d/Y", strtotime($data["client_birthday"])), ""),
                array("<a href=\"?" . $str_get . "&page=edit&id={$data[client_id]}\">edit</a>&nbsp;&nbsp;<a href=\"?" . $str_get . "&action=doDeleteClient&id={$data[client_id]}\">delete</a>","align=\"center\""),
                );
        return $dt;
    }

    // ----------------------------------------------------------------------------------
    // --- [ Render Clients Edit page ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    function renderClientsEditPage(&$core, &$render, &$db)
    {
        $sql = "select client_id, client_email, client_name, client_password, client_birthday, client_phone, client_billing_name, client_billing_city,";
        $sql .= " client_billing_state, client_billing_country, client_billing_adress1, client_billing_adress2, client_billing_zip, client_billing_phone,";
        $sql .= " client_cctype, client_ccnumber, client_ccexpdate, client_ccholdername, client_cccvv, client_shipping_name, client_shipping_adress1,";
        $sql .= " client_shipping_adress2, client_shipping_city, client_shipping_state, client_shipping_zip, client_shipping_country, mail_groups, balance";
        $sql .= " from clients where client_id = " . $_GET['id'];
        
        $info_client = ArrayDb2Str($db->getAll($sql));

// Output Errors
        if (isset($_GET['error']))
        {
            switch ($_GET['error'])
            {
                case "email" :
                        $render->assign("error_email", "This Email(login) is exist.");
                        $info_client[0]['client_email'] = $_POST['client_email'];
                    break;

                case "password" :
                        $render->assign("error_password", "Wrong password.");
                    break;
                    
                default :
                    break;

            }
        }

        $info_client[0]['mail_groups'] = str_replace("<", "", $info_client[0]['mail_groups']);
        $info_client[0]['mail_groups'] = split(">", $info_client[0]['mail_groups']);

        $render->assign("info_client", $info_client[0]);


        $str_get = isset($_GET['st_paginator_page']) ? "&st_paginator_page=" . $_GET['st_paginator_page'] : "";
        $str_get .= isset($_GET['st_paginator_ppv']) ? "&st_paginator_ppv=" . $_GET['st_paginator_ppv'] : "";
        $render->assign("str_get", $str_get);


        $sql = "select name, group_id from mail_groups where is_active = 1";
        $list_mail_groups =  $db->getAll($sql);
        $render->assign("list_mail_groups", ArrayDb2Str($list_mail_groups));


        // -------- History products Begin
        $history_products = $core->getSnippet("historyproducts");
        $params_history_products = array
        (
            'prod_id' => "",
            'limit_records' => "",
            'user_id' => $_GET['id']
        );
        
        $arr_history = $history_products->getHistoryRecords($params_history_products);
        $arr_info_products = array();
        
        foreach ($arr_history as $product)
        {
            $sql = "select catalog_id, title, img_small, parent_id from catalog where catalog_id = " . $product['product_id'];
            $info_product = ArrayDb2Str($db->getAll($sql));
            $arr_info_products[$product['product_id']]['prod_info'] = $info_product[0];

            if (file_exists($core->config["file_root"] . "/inventory/" . $arr_info_products[$product['product_id']]['prod_info']['img_small']))
            {
                $arr_info_products[$product['product_id']]['prod_info']['img_small'] = "./inventory/" . $arr_info_products[$product['product_id']]['prod_info']['img_small'];
            }
            else
            {
                $arr_info_products[$product['product_id']]['prod_info']['img_small'] = "./img/no_image.jpg";
            }
        }

        $render->assign("list_history_products", ArrayDb2Str($arr_info_products));
        // -------- History products End


        return "client_edit.tpl.php";
    }

};


?>